﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using UIObjects.TreeViewInterfaces;
using System.Collections.ObjectModel;
using TreeBuilder.Contracts;
using MvvmTreeView;
using System.Windows.Controls;
using System.Windows;
using SL4PopupMenu;
using System.Collections.Specialized;
using AbstraX.ClientInterfaces;
using System.Diagnostics;

namespace TreeBuilder.ViewModels
{
    public class TreeBuilderRoot : TreeBuilderTreeNodeBase
    {
        private ITreeBuilderRoot root;
        private string name;
        private bool allowDrop;
        private List<IContextMenuItem> subMenus;
        private ObservableCollection<IElement> potentialRootSources;

        public TreeBuilderRoot(ITreeBuilderService treeBuilderService, ITreeView treeView, ITreeBuilderRoot root, ITreeNode parent) : base(treeBuilderService, treeView, parent)
        {
            this.root = root;
            this.Tag = root;
            this.allowDrop = true;
        }

        public override ITreeNodeBase InternalNodeObject
        {
            get
            {
                return root;
            }
        }

        public override void OnSelect()
        {
        }

        public override void Expand()
        {
            if (!this.IsChildrenLoaded)
            {
                root.ChildrenLoaded += new TreeBuilder.Contracts.ChildrenLoadedHandler(OnChildrenLoaded);
                root.LoadChildren();
            }

            base.Expand();
        }

        public override string Text
        {
            get
            {
                return root.Text;
            }

            set
            {
                var oldValue = root.Text;

                root.UpdatedSuccessfully += (node, e) =>
                {
                    
                };

                root.Text = value;
            }
        }

        private List<IContextMenuItem> GetSubMenus()
        {
            if (potentialRootSources == null)
            {
                Debug.WriteLine("Call to GetSubMenus.  Setting potentialRootSources");

                potentialRootSources = treeBuilderService.GetPotentialRootSources();

                ((INotifyCollectionChanged)potentialRootSources).CollectionChanged += new NotifyCollectionChangedEventHandler(PotentialRootSourcesCollectionChanged);

                PotentialRootSourcesCollectionChanged(this, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset));
            }

            return subMenus;
        }

        private void BuildTree(object sender, RoutedEventArgs ea)
        {
            var menu = (PopupMenuItem)sender;
        }

        private void AddRootSource(object sender, RoutedEventArgs ea)
        {
            var menu = (PopupMenuItem)sender;

            if (potentialRootSources.Any(e => e.Name == (string)menu.Tag))
            {
                var element = potentialRootSources.Single(e => e.Name == (string)menu.Tag);
                var createOperation = treeBuilderService.CreateRootSourceNode(root, element);

                createOperation.NodeCreated += (parent, e) =>
                {
                    this.Nodes.Add(new TreeBuilderTreeNodeRootSource(treeBuilderService, treeView, createOperation.NewNode, this) { ChildOrdinal = this.Nodes.Count });
                    base.Expand();
                };
            }
        }

        private void PotentialRootSourcesCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            subMenus = new List<IContextMenuItem>();

            if (this.TreeView.Log != null)
            {
                this.TreeView.Log.Debug("Root Sources Collection Changed");
            }

            Debug.WriteLine("Root Sources Collection Changed ******************************************");

            if (potentialRootSources.Count() > 0)
            {
                foreach (IElement element in potentialRootSources)
                {
                    if (this.TreeView.Log != null)
                    {
                        this.TreeView.Log.Debug("-- Adding " + element.Name);
                    }

                    Debug.WriteLine("-- Adding " + element.Name);

                    if (subMenus.Any(s => s.ID == element.ID))
                    {
                        Debugger.Break();
                    }

                    subMenus.Add(new ContextMenuItem(element.ID, null, element.Name, element.Name, AddRootSource));
                }
            }
            else
            {
                Debug.WriteLine("-- No items");
            }

            Debug.WriteLine("End Root Sources Collection Changed **************************************");

            treeView.ResetNodeMenu(this);
        }

        public override ContextMenu ContextMenu
        {
            get
            {
                var contextMenu = new ContextMenu
                {
                    Items = new List<IContextMenuItem>()
                    {
                        new ContextMenuItem
                        {
                            Text = "Add Root Source",
                            Items = GetSubMenus()
                        },
                        new ContextMenuItem
                        {
                            Text = "Build...",
                            ClickHandler = BuildTree
                        }
                    }
                };

                return contextMenu;
            }

            set
            {
                contextMenu = value;
            }
        }

        public override bool? HasChildren
        {
            get { throw new NotImplementedException(); }
        }

        public override string ID
        {
            get 
            {
                return root.ID;
            }
        }

        public override void LoadChildren()
        {
            root.ChildrenLoaded += new TreeBuilder.Contracts.ChildrenLoadedHandler(OnChildrenLoaded);
            root.LoadChildren();
        }

        public override IEnumerable<ITreeNodeBase> Children
        {
            get 
            {
                return root.Children;
            }
        }

        public override void Remove()
        {
            MessageBox.Show("Root node cannot be deleted");
        }

        public override IBase BaseObject
        {
            get { throw new NotImplementedException(); }
            set { throw new NotImplementedException(); }
        }

        public override bool AllowDrop
        {
            get
            {
                return allowDrop;
            }
            set
            {
                allowDrop = value;
            }
        }

        public override ITreeNode ShallowClone()
        {
            throw new NotImplementedException();
        }

        public override ITreeNode DeepClone()
        {
            throw new NotImplementedException();
        }

        public override void AddNew(string shortCut)
        {
        }

        public override void DragStarting(object sender, UIObjects.DragDropInterfaces.ItemDragEventArgs e)
        {
        }

        public override void DragCompleted(object sender, UIObjects.DragDropInterfaces.ItemDragEventArgs e)
        {
        }

        public override void ItemDropped(object sender, UIObjects.DragDropInterfaces.ItemDragEventArgs e, int insertionIndex)
        {
        }

        public override void GiveFeedback(object sender, UIObjects.DragDropInterfaces.GiveFeedbackEventArgs e)
        {
        }

        public override bool AllowRename
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        public override bool HasLayoverImage<T>(out T image)
        {
            return root.HasLayoverImage<T>(out image);
        }

        public override void DragEnter(object sender, UIObjects.DragDropInterfaces.DragEventArgs e)
        {
        }

        public override void DragLeave(object sender, UIObjects.DragDropInterfaces.DragEventArgs e)
        {
        }

        public override void DragOver(object sender, UIObjects.DragDropInterfaces.DragEventArgs e)
        {
        }

        public override float ChildOrdinal
        {
            get
            {
                return root.ChildOrdinal;
            }
            set
            {
                root.ChildOrdinal = value;
            }
        }
    }
}
